import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/expense_model.dart';
import '../services/expense_service.dart';

/// 记账条目列表Provider
final expenseListProvider =
    StateNotifierProvider<ExpenseListNotifier, List<ExpenseModel>>((ref) {
      return ExpenseListNotifier();
    });

/// 记账条目列表状态管理器
class ExpenseListNotifier extends StateNotifier<List<ExpenseModel>> {
  ExpenseListNotifier() : super([]) {
    loadExpenses();
  }

  /// 加载所有记账条目
  Future<void> loadExpenses() async {
    try {
      final expenses = ExpenseService.getAllExpenses();
      state = expenses;
    } catch (e) {
      // 处理错误
      print('Error loading expenses: $e');
    }
  }

  /// 添加记账条目
  Future<void> addExpense(ExpenseModel expense) async {
    try {
      await ExpenseService.addExpense(expense);
      state = [...state, expense]..sort((a, b) => b.date.compareTo(a.date));
    } catch (e) {
      print('Error adding expense: $e');
    }
  }

  /// 更新记账条目
  Future<void> updateExpense(ExpenseModel expense) async {
    try {
      await ExpenseService.updateExpense(expense);
      state = state.map((e) => e.id == expense.id ? expense : e).toList()
        ..sort((a, b) => b.date.compareTo(a.date));
    } catch (e) {
      print('Error updating expense: $e');
    }
  }

  /// 删除记账条目
  Future<void> deleteExpense(String id) async {
    try {
      await ExpenseService.deleteExpense(id);
      state = state.where((expense) => expense.id != id).toList();
    } catch (e) {
      print('Error deleting expense: $e');
    }
  }

  /// 清空所有数据
  Future<void> clearAll() async {
    try {
      await ExpenseService.clearAllData();
      state = [];
    } catch (e) {
      print('Error clearing expenses: $e');
    }
  }
}

/// 当前月份记账条目Provider
final currentMonthExpensesProvider = Provider<List<ExpenseModel>>((ref) {
  final allExpenses = ref.watch(expenseListProvider);
  final now = DateTime.now();
  final startOfMonth = DateTime(now.year, now.month, 1);
  final endOfMonth = DateTime(now.year, now.month + 1, 0);

  return allExpenses.where((expense) {
    return expense.date.isAfter(
          startOfMonth.subtract(const Duration(days: 1)),
        ) &&
        expense.date.isBefore(endOfMonth.add(const Duration(days: 1)));
  }).toList();
});

/// 收入记账条目Provider
final incomeExpensesProvider = Provider<List<ExpenseModel>>((ref) {
  final allExpenses = ref.watch(expenseListProvider);
  return allExpenses
      .where((expense) => expense.type == ExpenseType.income)
      .toList();
});

/// 支出记账条目Provider
final expenseExpensesProvider = Provider<List<ExpenseModel>>((ref) {
  final allExpenses = ref.watch(expenseListProvider);
  return allExpenses
      .where((expense) => expense.type == ExpenseType.expense)
      .toList();
});

/// 总收入Provider
final totalIncomeProvider = Provider<double>((ref) {
  final incomeExpenses = ref.watch(incomeExpensesProvider);
  return incomeExpenses.fold(0.0, (sum, expense) => sum + expense.amount);
});

/// 总支出Provider
final totalExpenseProvider = Provider<double>((ref) {
  final expenseExpenses = ref.watch(expenseExpensesProvider);
  return expenseExpenses.fold(0.0, (sum, expense) => sum + expense.amount);
});

/// 净收入Provider（收入 - 支出）
final netIncomeProvider = Provider<double>((ref) {
  final totalIncome = ref.watch(totalIncomeProvider);
  final totalExpense = ref.watch(totalExpenseProvider);
  return totalIncome - totalExpense;
});

/// 当月总收入Provider
final currentMonthIncomeProvider = Provider<double>((ref) {
  final currentMonthExpenses = ref.watch(currentMonthExpensesProvider);
  return currentMonthExpenses
      .where((expense) => expense.type == ExpenseType.income)
      .fold(0.0, (sum, expense) => sum + expense.amount);
});

/// 当月总支出Provider
final currentMonthExpenseProvider = Provider<double>((ref) {
  final currentMonthExpenses = ref.watch(currentMonthExpensesProvider);
  return currentMonthExpenses
      .where((expense) => expense.type == ExpenseType.expense)
      .fold(0.0, (sum, expense) => sum + expense.amount);
});

/// 当月净收入Provider
final currentMonthNetIncomeProvider = Provider<double>((ref) {
  final currentMonthIncome = ref.watch(currentMonthIncomeProvider);
  final currentMonthExpense = ref.watch(currentMonthExpenseProvider);
  return currentMonthIncome - currentMonthExpense;
});

/// 分类统计Provider
final categoryStatisticsProvider = Provider<Map<ExpenseCategory, double>>((
  ref,
) {
  final allExpenses = ref.watch(expenseListProvider);
  final Map<ExpenseCategory, double> statistics = {};

  for (final expense in allExpenses) {
    statistics[expense.category] =
        (statistics[expense.category] ?? 0.0) + expense.amount;
  }

  return statistics;
});

/// 收入分类统计Provider
final incomeCategoryStatisticsProvider = Provider<Map<ExpenseCategory, double>>(
  (ref) {
    final incomeExpenses = ref.watch(incomeExpensesProvider);
    final Map<ExpenseCategory, double> statistics = {};

    for (final expense in incomeExpenses) {
      statistics[expense.category] =
          (statistics[expense.category] ?? 0.0) + expense.amount;
    }

    return statistics;
  },
);

/// 支出分类统计Provider
final expenseCategoryStatisticsProvider =
    Provider<Map<ExpenseCategory, double>>((ref) {
      final expenseExpenses = ref.watch(expenseExpensesProvider);
      final Map<ExpenseCategory, double> statistics = {};

      for (final expense in expenseExpenses) {
        statistics[expense.category] =
            (statistics[expense.category] ?? 0.0) + expense.amount;
      }

      return statistics;
    });

/// 最近记账条目Provider（最近10条）
final recentExpensesProvider = Provider<List<ExpenseModel>>((ref) {
  final allExpenses = ref.watch(expenseListProvider);
  return allExpenses.take(10).toList();
});

/// 选中的日期范围Provider
final selectedDateRangeProvider = StateProvider<DateTimeRange?>((ref) => null);

/// 根据选中日期范围过滤的记账条目Provider
final filteredExpensesProvider = Provider<List<ExpenseModel>>((ref) {
  final allExpenses = ref.watch(expenseListProvider);
  final dateRange = ref.watch(selectedDateRangeProvider);

  if (dateRange == null) {
    return allExpenses;
  }

  return allExpenses.where((expense) {
    return expense.date.isAfter(
          dateRange.start.subtract(const Duration(days: 1)),
        ) &&
        expense.date.isBefore(dateRange.end.add(const Duration(days: 1)));
  }).toList();
});

/// 搜索关键词Provider
final searchKeywordProvider = StateProvider<String>((ref) => '');

/// 根据搜索关键词过滤的记账条目Provider
final searchedExpensesProvider = Provider<List<ExpenseModel>>((ref) {
  final allExpenses = ref.watch(expenseListProvider);
  final keyword = ref.watch(searchKeywordProvider);

  if (keyword.isEmpty) {
    return allExpenses;
  }

  return allExpenses.where((expense) {
    return expense.description.toLowerCase().contains(keyword.toLowerCase()) ||
        expense.category.displayName.contains(keyword);
  }).toList();
});

/// 月度统计数据Provider
final monthlyStatisticsProvider = Provider.family<Map<String, double>, int>((
  ref,
  year,
) {
  final allExpenses = ref.watch(expenseListProvider);
  final Map<String, double> monthlyStats = {};

  for (int month = 1; month <= 12; month++) {
    final startOfMonth = DateTime(year, month, 1);
    final endOfMonth = DateTime(year, month + 1, 0);

    final monthExpenses = allExpenses.where((expense) {
      return expense.date.isAfter(
            startOfMonth.subtract(const Duration(days: 1)),
          ) &&
          expense.date.isBefore(endOfMonth.add(const Duration(days: 1)));
    }).toList();

    double income = 0.0;
    double expense = 0.0;

    for (final item in monthExpenses) {
      if (item.type == ExpenseType.income) {
        income += item.amount;
      } else {
        expense += item.amount;
      }
    }

    monthlyStats['${month}_income'] = income;
    monthlyStats['${month}_expense'] = expense;
    monthlyStats['${month}_net'] = income - expense;
  }

  return monthlyStats;
});
